605. 种花问题

605. 种花问题

Similar Question

leading to the advanced question

Solution Tips

有的时候真的很难理解为啥是贪心

方案一: 贪心

p9bc43t.png

public boolean canPlaceFlowers(int[] flowerbed, int n) {
	for (int i = 0, len = flowerbed.length; i < len && n > 0;) {
		if (flowerbed[i] == 1) {
			i += 2;
		} else if (i == flowerbed.length - 1 || flowerbed[i + 1] == 0) {
			n--;
			i += 2;
		} else {
			i += 3;
		}
	}
	return n <= 0;
}